/**
 * Created by leo on 2017/3/6.
 */
declare var $:any;

interface IAjaxHandler {
  handleSuccess: (data: any) => void;
  handleError: (code: string, message: string) => void;
  handleComplete: () => void;
}

function recognitionError(message: string): string {
  const arr = message.split(':');
  if (arr.length === 3) {
    return arr[2];
  }
  return message;
}

export const API_SUCCESS = '10200';

export function doAjax(setting: any | IAjaxHandler): void {
  const handles = <IAjaxHandler>setting;
  const _setting = {
    xhrFields: {
      withCredentials: true
    },
    crossDomain: true,
    type: 'post',
    headers: {
      Accept: 'application/vnd.cas-sso-1.1+json'
    },
    dataType: 'json',
    error: function(XMLHttpRequest: any, textStatus: any) {
      console.error('服务器请求失败， 请求失败, status: ' + XMLHttpRequest.status + ' , readyState: ' + XMLHttpRequest.readyState + ' , textStatus: ' + textStatus);
      if (handles.handleError) {
        handles.handleError('10500', '失败, 请稍后重试！');
      }
    },
    success: (result) => {
      if (result.code !== API_SUCCESS) {
        console.error('接口失败， code: ' + result.code + ', message: ' + result.message);
        if (handles.handleError) {
          handles.handleError(result.codc, recognitionError(result.message));
        }
        return;
      }

      if (handles.handleSuccess) {
        handles.handleSuccess(result.data);
      }
    },
    complete: () => {
      if (handles.handleComplete) {
        handles.handleComplete();
      }
    }
  };

  $.ajax($.extend({}, _setting, setting));
}
